<template>
  <div class="history-query-container">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="报警时间">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="报警级别">
          <el-select v-model="queryParams.alarmLevel" placeholder="全部级别" clearable multiple style="width: 200px">
            <el-option label="紧急" :value="1" />
            <el-option label="重要" :value="2" />
            <el-option label="一般" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="报警来源">
          <el-select v-model="queryParams.sourceIds" placeholder="全部来源" clearable multiple filterable style="width: 200px">
            <el-option 
              v-for="source in sourceList" 
              :key="source.id" 
              :label="source.sourceName" 
              :value="source.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="queryParams.status" placeholder="全部状态" clearable multiple style="width: 200px">
            <el-option label="未处理" :value="1" />
            <el-option label="已推送未接收" :value="2" />
            <el-option label="已接收待处理" :value="3" />
            <el-option label="处理中" :value="4" />
            <el-option label="已闭环" :value="5" />
            <el-option label="已驳回" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="报警内容">
          <el-input 
            v-model="queryParams.alarmContent" 
            placeholder="请输入报警内容关键词" 
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleConfig">报警配置</el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
      <el-button type="info" @click="handleRefresh">刷新</el-button>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card>
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="alarmCode" label="报警编码" width="150" />
        <el-table-column prop="sourceName" label="报警来源" width="120" />
        <el-table-column prop="alarmType" label="报警类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlarmTypeTag(row.alarmType)">
              {{ getAlarmTypeName(row.alarmType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alarmLevel" label="报警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlarmLevelTag(row.alarmLevel)">
              {{ getAlarmLevelName(row.alarmLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alarmContent" label="报警内容" show-overflow-tooltip />
        <el-table-column prop="triggerTime" label="触发时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.triggerTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handlerName" label="处理人" width="100" />
        <el-table-column prop="handleTime" label="处理时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.handleTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleDetail(row)">详情</el-button>
            <el-button v-if="row.status === 4" type="warning" size="small" @click="handleReview(row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </el-card>
    
    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="报警详情" width="60%">
      <AlarmDetail :alarm-id="currentAlarmId" v-if="detailDialogVisible" />
    </el-dialog>
    
    <!-- 审核弹窗 -->
    <el-dialog v-model="reviewDialogVisible" title="审核报警处理" width="50%">
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="120px">
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-radio-group v-model="reviewForm.reviewStatus">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">审核驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="reviewOpinion">
          <el-input 
            v-model="reviewForm.reviewOpinion" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { queryHistoryAlarms, exportAlarmData, getAllSources, reviewAlarm, getAlarmDetail } from '@/api/prod_operate/alarm_management'
import AlarmDetail from './AlarmDetail.vue'

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const sourceList = ref([])
const selectedRows = ref([])
const detailDialogVisible = ref(false)
const reviewDialogVisible = ref(false)
const currentAlarmId = ref(null)
const reviewFormRef = ref(null)

const dateRange = ref([])

const queryParams = ref({
  startTime: null,
  endTime: null,
  alarmLevel: [],
  sourceIds: [],
  status: [],
  alarmContent: '',
  pageNum: 1,
  pageSize: 10
})

const reviewForm = ref({
  id: null,
  reviewStatus: null,
  reviewOpinion: '',
  reviewerId: 'current_user'
})

const reviewRules = {
  reviewStatus: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
  reviewOpinion: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
}

const getFileName = (prefix) => {
  const now = new Date()
  const pad = (num) => num.toString().padStart(2, '0')
  return `${prefix}_${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.xlsx`
}

const downloadExcel = async (data, fileName) => {
  if (!data) {
    ElMessage.error('导出失败：返回数据为空')
    return
  }
  const blob = data instanceof Blob ? data : new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  if (blob.type === 'application/json') {
    const text = await blob.text()
    try {
      const err = JSON.parse(text)
      ElMessage.error(err.msg || '导出失败')
    } catch (error) {
      ElMessage.error('导出失败')
    }
    return
  }
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

// 获取报警来源列表
const fetchSources = async () => {
  try {
    const res = await getAllSources()
    if (res.code === 200) {
      sourceList.value = res.data || []
    }
  } catch (error) {
    console.error('获取报警来源失败：', error)
  }
}

// 查询数据
const handleQuery = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams.value,
      startTime: dateRange.value?.[0] || null,
      endTime: dateRange.value?.[1] || null
    }
    const res = await queryHistoryAlarms(params)
    if (res.code === 200) {
      tableData.value = res.data.data || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '查询失败')
    }
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  queryParams.value = {
    startTime: null,
    endTime: null,
    alarmLevel: [],
    sourceIds: [],
    status: [],
    alarmContent: '',
    pageNum: 1,
    pageSize: 10
  }
  handleQuery()
}

// 日期变化
const handleDateChange = () => {
  // 日期变化时自动查询
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 查看详情
const handleDetail = (row) => {
  currentAlarmId.value = row.id
  detailDialogVisible.value = true
}

// 审核
const handleReview = async (row) => {
  try {
    const detailRes = await getAlarmDetail(row.id)
    if (detailRes.code !== 200 || !detailRes.data?.handleRecord) {
      ElMessage.error(detailRes.msg || '未找到对应的处理记录，无法审核')
      return
    }
    reviewForm.value.id = detailRes.data.handleRecord.id
    reviewForm.value.reviewStatus = null
    reviewForm.value.reviewOpinion = ''
    reviewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取处理记录失败：' + error.message)
  }
}

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return
  
  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await reviewAlarm(reviewForm.value)
        if (res.code === 200) {
          ElMessage.success('审核成功')
          reviewDialogVisible.value = false
          handleQuery()
        } else {
          ElMessage.error(res.msg || '审核失败')
        }
      } catch (error) {
        ElMessage.error('审核失败：' + error.message)
      }
    }
  })
}

// 报警配置
const handleConfig = () => {
  ElMessage.info('报警配置功能开发中')
}

// 导出
const handleExport = async () => {
  try {
    const params = {
      ...queryParams.value,
      startTime: dateRange.value?.[0] || null,
      endTime: dateRange.value?.[1] || null
    }
    if (selectedRows.value.length > 0) {
      params.alarmIds = selectedRows.value.map(item => item.id)
    }
    const res = await exportAlarmData(params)
    await downloadExcel(res, getFileName('报警历史数据'))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  }
}

// 刷新
const handleRefresh = () => {
  handleQuery()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取报警类型标签
const getAlarmTypeTag = (type) => {
  const map = { 1: 'danger', 2: 'warning', 3: 'info' }
  return map[type] || 'info'
}

// 获取报警类型名称
const getAlarmTypeName = (type) => {
  const map = { 1: '设备故障', 2: '参数超标', 3: '通讯中断' }
  return map[type] || '未知'
}

// 获取报警级别标签
const getAlarmLevelTag = (level) => {
  const map = { 1: 'danger', 2: 'warning', 3: 'info' }
  return map[level] || 'info'
}

// 获取报警级别名称
const getAlarmLevelName = (level) => {
  const map = { 1: '紧急', 2: '重要', 3: '一般' }
  return map[level] || '未知'
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = { 
    1: 'info', 
    2: 'warning', 
    3: 'warning', 
    4: 'primary', 
    5: 'success', 
    6: 'danger' 
  }
  return map[status] || 'info'
}

// 获取状态名称
const getStatusName = (status) => {
  const map = { 
    1: '未推送', 
    2: '已推送未接收', 
    3: '已接收待处理', 
    4: '处理中', 
    5: '已闭环', 
    6: '已驳回' 
  }
  return map[status] || '未知'
}

onMounted(() => {
  fetchSources()
  handleQuery()
})
</script>

<style scoped>
.history-query-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.action-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

